package org.batatasframework.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public abstract class AbstractSupportHandler<T extends AbstractSupportDefinition> implements ApplicationContextAware, InitializingBean{

	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
	protected final CatalogDefinitionMapped<T> catalogMapped = new CatalogDefinitionMapped<>();
	
	private final DefinitionBuilder<T> builder = new DefinitionBuilder<T>(){
		private T currentDefinition;
		private String catalog;

		@Override
		public void addGroup(String catalog) {
			this.catalog = catalog;
		}

		@Override
		public T add(String key, String name) {
			currentDefinition = generateDefinition(key, name);
			catalogMapped.put(catalog, key, currentDefinition);
			log.info("新增加定义：" + currentDefinition);
			return currentDefinition;
		}
		
	};
	
	protected abstract T generateDefinition(String key, String name);
	
	protected ApplicationContext applicationContext;
	
	/** 通过配置文件注入进来的注册器 */
	protected DefinitionRegister<T>[] registers;
	
	public void setRegisters(DefinitionRegister<T>[] registers) {
		this.registers = registers;
	}

	@Override
	public void afterPropertiesSet() throws Exception { 
		if(null != registers){
			for(DefinitionRegister<T> register : registers){
				register.register(builder);
			}
		}
		
		catalogMapped.finish();
	}
	
	@Override
	public final void setApplicationContext(ApplicationContext context) throws BeansException {
		applicationContext = context;
	}

	public Iterable<T> getDefinitions(String catalog) {
		return catalogMapped.iterable(catalog);
	}

	public T get(String catalog, String key) {
		return catalogMapped.find(catalog, key);
	}
}
